package cn.com.counter.core;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 计数整理任务
 * @author Cevin Yang
 *
 */
public class CounterTask extends TimerTask{

	private static final long DAY_LONG = 24L*60*60*1000;

	private static Counter counter = null;
	
	public void begin(){
		Timer timer = new Timer(true);
		System.out.println("["+getCurrentTime()+"] CounterTask 第一次执行时间 --> " + getBeginDate());
		timer.schedule(this, getBeginDate(), DAY_LONG);
	}
	
	@Override
	public void run() {
		System.out.println("["+getCurrentTime()+"] CounterTask 开始执行");
		counter.updateAllBuffer2Db();		
		System.out.println("["+getCurrentTime()+"] 缓存数据更新到数据库完成");
		counter.updateDataOfYesterday();
		counter.clearDataOfToday();
		System.out.println("["+getCurrentTime()+"] 每日数据更新完成");
		if(isBeginOfWeek()){
			counter.updateDataOfLastWeek();
			counter.clearDataOfThisWeek();
			System.out.println("["+getCurrentTime()+"] 每周数据更新完成");
		}
		if(isBeginOfMonth()){
			counter.updateDataOfLastMonth();
			counter.clearDataOfThisMonth();
			System.out.println("["+getCurrentTime()+"] 每月数据更新完成");
		}
		System.out.println("["+getCurrentTime()+"] CounterTask 执行结束");
	}
	
	private boolean isBeginOfWeek(){
		Calendar calendar = Calendar.getInstance();
		int w = calendar.get(Calendar.DAY_OF_WEEK);
		return w==1;
	}
	
	private boolean isBeginOfMonth(){
		Calendar calendar = Calendar.getInstance();
		int m = calendar.get(Calendar.DAY_OF_MONTH);
		return m==1;
	}
	
	private Date getBeginDate(){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String todayStr = formatter.format(date);
		
		try {
			Date today = formatter.parse(todayStr);
			long tomorrowLong = today.getTime() + DAY_LONG;
			Date tomorrow = new Date(tomorrowLong);
			return tomorrow;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getCurrentTime(){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = new Date();
		String todayStr = formatter.format(date);
		return todayStr;
	}
	
	public static void main(String[] args) {
		System.out.println(getCurrentTime());
		Calendar calendar = Calendar.getInstance();
		System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
		System.out.println(getCurrentTime());
	}

}
